<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\AdminUserRule;
use app\validate\AdminRule;
use think\exception\ValidateException;
use think\Request;
use think\facade\View;

class Tool extends AdminBase
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    public function buildRule(Request $request)
    {
        if ($request->isPost()) {
            $ruleModel = new AdminUserRule();
            $data      = $request->post();

            $menuRules = rtrim($data['menu_rules'], '/');
            $tmp       = explode('/', $menuRules);
            if (count($tmp) != 4) {
                $this->error('菜单格式错误!必须为:/admin/控制器/方法');
            }
            $info = $ruleModel->where(['type' => 'menu', 'rules' => $data['menu_rules']])->find();
            if (!$info instanceof $ruleModel) {
                $this->error('菜单不存在:'.$data['menu_rules'] );
            }
            foreach ($data['rule'] as $k => $v) {
                $arr   = explode(':', $v);
                $name  = $arr[0];
                $rules = '/' . $tmp[1] . '/' . $tmp[2] . '/' . $arr[1];
                $this->addRule($info['id'], $name, $rules);
            }

        } else {
            return View::fetch();
        }
    }

    /**
     * 添加节点
     * @param int $pid
     * @param string $name
     * @param string $rules
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function addRule(int $pid, string $name, string $rules)
    {
        $ruleModel = new AdminUserRule();
        $info      = $ruleModel->where(['rules' => $rules])->find();
        if ($info instanceof $ruleModel) {
            //存在
            return true;
        } else {
            $rs = $ruleModel->save(['pid' => $pid, 'type' => 'node', 'name' => $name, 'rules' => $rules]);
            if ($rs) {
                //清除菜单缓存
                clearRedisCache('admin:menu_html:*');
                return true;
            } else {
                return false;
            }
        }
    }
}
